package edu.zut.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 *
 */
@WebServlet(name = "SessionDemo" ,value = "/session/demo1")
public class SessionDemo extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //通过请求获取session, 如果存在对应的session，直接使用，如果不存在，就创建
        HttpSession session = request.getSession();
        //判断session是否是新建的
        if (session.isNew()) {
            System.out.println("当前session是新建的");
        }else {
            System.out.println("当前session是旧的");
        }
        //session都要一个id
        String id = session.getId();

        //session id 的保存机制
        Cookie cookie = new Cookie("JSESSIONID", id);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        //关闭浏览器后，重新打开发起请求依然能携带id
        cookie.setMaxAge(60*60);
        //session的默认生命周期是30分钟
        session.setMaxInactiveInterval(60*60);

        //session保存数据
        session.setAttribute("myName","xueyin");
        session.setAttribute("myAge",20);
        //获取数据
        Object myName = session.getAttribute("myName");
        System.out.println("myName = " + myName);
        //移除数据
        session.removeAttribute("myAge");

        response.addCookie(cookie);
        response.getWriter().write(id);

    }
}
